package com.yorick.common.security;

import com.alibaba.fastjson.JSONObject;
import com.yorick.common.config.jedis.JedisClient;
import com.yorick.common.util.RSAUtils;
import com.yorick.common.util.ResponseWriter;
import com.yorick.login.enums.Account;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: LoginInterceptor
 * @description: 登录拦截器
 * @author: Yorick
 * @create: 31/5/2022
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    JedisClient jedisClient;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        JSONObject result = new JSONObject();
        if (session.getAttribute(Account.account.toString()) != null) {
            String privateKey = jedisClient.get(
                    session.getAttribute(Account.account.toString()).toString() + "_token"
            );
            String token = RSAUtils.decrypt(session.getAttribute("token").toString(), privateKey);
            if (token.equals(session.getAttribute(Account.account.toString()).toString())) {
                return true;
            }
        }

        result.put("flag", "-1");
        result.put("msg", "登录失效，请重新登录");
        ResponseWriter.responseOutWithJson(httpServletResponse, result);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}